package com.yiwu.common.utils;

import cn.hutool.http.HttpRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yiwu.common.config.WeiXinConfig;
import com.yiwu.common.enums.ResponseCode;
import com.yiwu.common.exception.BusinessException;
import com.yiwu.common.model.WeiXinResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @description TODO
 * @date 2024/5/24 23:22
 */
@Slf4j
@Component
public class WeiXinUtil {

    @Resource
    private WeiXinConfig weiXinConfig;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Scheduled(fixedRate = 116 * 60 * 1000)
    public void updateAck() {
        try {

            String args = JsonUtil.toJsonString(weiXinConfig);

            String urlString = "https://api.weixin.qq.com/cgi-bin/stable_token";
            String body = HttpRequest.post(urlString)
                    .body(args)
                    .execute().body();

            ObjectMapper objectMapper = new ObjectMapper();

            // 将JSON字符串转换为Java对象
            WeiXinResponse weiXinResponse = objectMapper.readValue(body, WeiXinResponse.class);

            stringRedisTemplate.opsForValue().set("yiwu-weixin", weiXinResponse.getAccess_token(), 120, TimeUnit.MINUTES);
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.WEIXIN_ERROR);
        }
    }
}
